import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from "@/stores";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      //登录页
      name: "login",
      path: "/login",

      component: () => import("@/views/login/LoginPage.vue"),
    },
    {
      //布局架子
      path: "/",
      component: () => import("@/views/layout/LayoutContainer.vue"),
      //重定向到文章管理
      redirect: "/manage/notice",
      //配置二级路由
      children: [
        // 借阅管理
        {
          name: "manage",
          path: "/manage/borrow",
          component: () => import("@/views/function/BorrowManage.vue"),
        },
        // 图书管理
        {
          name: "book",
          path: "/manage/book",
          component: () => import("@/views/function/BookManage.vue"),
        },
        //读者管理
        {
          name: "reader",
          path: "/manage/reader",
          component: () => import("@/views/function/ReaderManage.vue"),
        },
        //类型管理
        {
          name: "type",
          path: "/manage/type",
          component: () => import("@/views/function/TypeManage.vue"),
        },
        // 公告管理
        {
          name: "notice",
          path: "/manage/notice",
          component: () => import("@/views/function/NoticeManage.vue"),
        },
        //统计分析
        {
          name: "statistics",
          path: "/statistics/statistics",
          component: () => import("@/views/statistics/Statistics..vue"),
        },
        // 用户详情
        {
          name: "userDetail",
          path: "/user/detail",
          component: () => import("@/views/user/UserDetail.vue"),
        },
        // 更换头像
        {
          name: "userAvatar",
          path: "/user/avatar",
          component: () => import("@/views/user/UserAvatar.vue"),
        },
        // 更换密码
        {
          name: "userPassword",
          path: "/user/password",
          component: () => import("@/views/user/UserPassword.vue"),
        },
      ],
    },
  ],
});

// 路由守卫
router.beforeEach(async (to, from) => {
  // 判断用户是否登录
  const userStore = useUserStore();
  if (!userStore.token && to.path !== "/login") {
    // 重定向到登录页面
    return "/login";
  }
});

export default router;
